<template>
  <div class="container">
    <div class="tree-box">
      <el-tree :data="treeData" default-expand-all v-loading="loading"
          element-loading-background="rgba(0, 0, 0, 0.5)"
          element-loading-spinner="el-icon-loading"
          :height="500"
          >
        <div class="custom-tree-node" slot-scope="{ node, data }"   @click="clickPlaneInfo(data)" @dblclick="dblclickPlaneInfo(data)">
          <div class="label" :class="{ 'leaf-node': node.isLeaf }" >
            {{ data.label }}
          </div>
          <div class="tree-time" v-if="data.lastSeenTime"">
            {{ data.lastSeenTime }}
          </div>
        </div>
      </el-tree>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import moment from "moment";
import { debounce } from 'lodash';
export default {
  name: "ltTreeDate",
  components: {},
  props: {},
  data() {
    return {
      treeData: [],
      loading:true,
      debouncedClick: null
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.getTreeData();
    this.$nextTick(()=>{
      this.$bus.$on('newPlaneInfo',this.addTreeData)
    })
    
  },
  created() {
    this.debouncedClick = debounce(this.emitClickPlaneInfo, 300);
  },
  beforeDestroy() {
        // 组件销毁时取消防抖
        this.debouncedClick.cancel();
        this.$bus.$off('newPlaneInfo')
  },
  methods: {
    getTreeData() {
      axios({
        url: config.jkUrl + "/flightActivityDaily/getDailyStats",
        method: "get",
      }).then(
        (res) => {
          if (res.data.code == 0) {
            console.log(res.data.data);
            this.loading = true;
            setTimeout(() => {
              this.shuchuDataToTree(res.data.data);
              this.loading = false
            }, 200);
          }else if(res.data.code == -1){
            console.log("数据获取失败！",res);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    /**
     * 生成 [min, max] 范围内的随机整数
     * @param {number} min - 最小值（包含）
     * @param {number} max - 最大值（包含）
     * @returns {number} 随机整数
     */
    getRandomInt(min, max) {
      if (min === max) return min;
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    shuchuDataToTree(data){
      let treeData = data.map(item => this.randomAircaftHandle(item));
      const groupConfig = ["airline", "aircraftType","icaoCode"];
      this.treeData = this.organizationTreeDataByList(treeData, groupConfig);
      this.$bus.$emit("drawplanedata",treeData)
    },
    randomAircaftHandle(item) {
      let airLineArr = [
        "国际航空",
        "南方航空",
        "东方航空",
        "四川航空",
        "春秋航空",
        "海南航空",
      ];
      let aircraftTypeArr = [
        "空客A320neo",
        "空客A350-900",
        "空客A380",
        "波音737 MAX 8",
        "波音777-300ER",
        "波音787-9",
        "COMAC C919",
      ];
        const randomAirlineIndex = this.getRandomInt(0, airLineArr.length - 1);
        const randomAircraftIndex = this.getRandomInt(
          0,
          aircraftTypeArr.length - 1
        );
        // let lastsendtime = item.lastSeenTime.slice(11, -4);
        let lastsendtime;
        if (!item.lastSeenTime) {
          lastsendtime = moment().format("HH:mm:ss");
        } else {
          lastsendtime = moment(item.lastSeenTime, "YYYY-MM-DD HH:mm:ss SSS").format("HH:mm:ss");
        }
        return {
          ...item, // 展开运算符保留原有属性
          airline: airLineArr[randomAirlineIndex],
          aircraftType: aircraftTypeArr[randomAircraftIndex],
          icaoCode: item.icaoCode,
          lastSeenTime: lastsendtime,
        };
    },
    organizationTreeDataByList(list, groupConfig) {
      let organizationTree = (tree, data, index) => {
        let group = _.groupBy(data, groupConfig[index]);
        if (index === groupConfig.length - 1) {
          data.forEach((o) => {
            tree.push({ ...o, label: o[groupConfig[index]] });
          });
        } else {
          Object.keys(group).forEach((item) => {
            let obj = {
              label: `${item}(${group[item].length})`,
              children: [],
            };
            organizationTree(obj.children, group[item], index + 1);
            tree.push(obj);
          });
        }
      };
      let returnArr = [];
      organizationTree(returnArr, list, 0);
      return returnArr;
    },
    emitClickPlaneInfo(data) {
      this.$bus.$emit("clickPlaneInfo", data.icaoCode);
    },
    clickPlaneInfo(data) {
      this.debouncedClick(data);
    },
    dblclickPlaneInfo(data) {
      this.debouncedClick.cancel(); 
      this.$bus.$emit("dblclickPlaneInfo", data.icaoCode);
    },
    addTreeData(data){
    const singleData = this.randomAircaftHandle(data);
     console.log("el树拿到新飞机的数据@@@@@@@@@@@@@@@@@@",singleData);
    },
  },
};
</script>

<style lang="less" scoped>
// 原本scss换成了less
.container {
  width: 100%;
  height: 100%;
  .tree-box {
    height: 100%;
    width: 400px;
    padding: 5px;
    /deep/ .el-tree {
      height: 100%;
      overflow-y: auto;
      background-color: transparent;
      color: #efefef;
      box-sizing: border-box;
      &::-webkit-scrollbar {
        width: 8px;
      }
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background: #1576e4b1;
        border-radius: 4px;
      }

      .el-tree-node {
        &:focus .el-tree-node__content {
          background-color: transparent;
        }
        // background-color: transparent;
        .el-tree-node__content {
          // background-color: transparent;

          &:hover {
            background-color: rgba(255, 255, 255, 0.3);
          }
          .custom-tree-node {
            position: relative;
            display: flex;
            flex: 1;
            .label {
              color: #e6a23c;
              &.leaf-node {
                color: white; // 叶子节点设置为白色
              }
            }
            .tree-time {
              position: absolute;
              right: 20px;
              color: #909399;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>
